package com.lmind.core.gps.terminal.protocol;

import java.nio.ByteBuffer;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.lmind.core.gps.terminal.message.AbstractMessage;

public class MinaProtocolEncoder extends ProtocolEncoderAdapter {
	
	private JsonMessageCodec objectCodec = new JsonMessageCodec();
	
	private PacketCodec packetCodec = new PacketCodec();

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		try {
			ByteBuffer data = objectCodec.encode((AbstractMessage)message);
			ByteBuffer packet = packetCodec.encode(data);
			out.write(IoBuffer.wrap(packet));
		} catch (Exception e) {
			session.close(true);
		}
	}

}
